package com.zzy.mccjt.gateway.common.filter;

import com.zzy.mccjt.gateway.common.filter.privacy.AbstractPrivacyHandle;
import com.zzy.mccjt.gateway.common.filter.privacy.PrivacyEncryptionHandle;
import com.zzy.mccjt.gateway.common.properties.PrivacyHandleProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

/**
 * description:接口响应数据处理:  处理body数据-->> 对隐私数据进行加密
 *
 * @author zzy
 * @version 1.0
 * @date 2020/4/3
 */
@Slf4j
@Component
public class EncryptionResponseBodyFilter/* extends ModifyResponseBodyGatewayFilterFactory*/ {

  /*  @PostConstruct
    public void init() {
        log.info("EncryptionResponseBodyFilter is ready to inject, order:{}",-2);
    }
    @Override
    public GatewayFilter apply(Config config) {

        return (exchange, chain) -> {
            ServerHttpRequest serverHttpRequest = exchange.getRequest();
            ServerHttpResponse serverHttpResponse= exchange.getResponse();
            if(HttpStatus.OK.equals(serverHttpResponse.getStatusCode())){
                *//*String contentType=serverHttpResponse.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
                if (!MediaType.MULTIPART_FORM_DATA_VALUE.equals(contentType)) {*//*
                    String path = serverHttpRequest.getPath().toString();
                    AbstractPrivacyHandle privacyHandle = SpringContextHolder.getBean(PrivacyEncryptionHandle.class);
                    PrivacyHandleProperties.HandleTarget target = privacyHandle.checkIsHandle(path);
                    if(target != null) {
                        config.setRewriteFunction(String.class, String.class, (webExchange, originContent) -> {
                            //数据加密
                            return Mono.just(privacyHandle.getData(path, originContent, target));
                        });
                    }
                *//*}*//*
            }else{
                log.warn(" response status is {}, unable to decrypt data ",serverHttpResponse.getStatusCode());
            }
            return chain.filter(exchange);
        };
    }*/
}
